var extensions = {};
extensions.image = ['png', 'jpg', 'jpeg', 'bmp', 'gif'];
extensions.txt = ['txt'];
extensions.excel = ['xls', 'xlsx', 'csv'];
extensions.word = ['doc', 'docx'];
extensions.ppt = ['ppt', 'pptx'];
extensions.pdf = ['pdf'];
extensions.video = ['mp4', 'm2v', 'mkv', 'rmvb', 'wmv', 'avi', 'flv', 'mov', 'm4v'];
extensions.audio = ['mp3', 'wav', 'wmv'];
extensions.zip = ['zip', 'rar', '7z'];

var fileAllExtensions = [];
for(let key in extensions){
	fileAllExtensions.push(extensions[key]);
}

//图片上传
var imgAccept = {
    title: 'Images',
    extensions: extensions.image,
    mimeTypes: 'image/jpg,image/jpeg,image/png'
};
//文件上传类型
var excelAccept = {
	title: 'Applications',
	extensions: extensions.excel,
	mimeTypes: 'application/xls,application/xlsx'
};

//pdf上传类型
var pdfAccept = {
	title: 'Applications',
	extensions: extensions.pdf,
	mimeTypes: 'application/pdf,application/PDF'
};

//文件上传类型
var fileAccept = {
	title: 'Applications',
	extensions: fileAllExtensions,
//	extensions: '*',
//	extensions: imgAccept.extensions + "," + excelAccept.extensions + "," + pdfAccept.extensions,
	mimeTypes: '*'
};

(function() {
    var $WebUpload = function(accept, uploadId, picWidth, picHeight, uploadUrl, isMultiple, multipleSize, valName, fn) {
    	this.uploadId = uploadId;
        this.pictureId = "filePicker_" + uploadId;
        this.uploadBtnId = "filePicker_" + uploadId + "_btn";
        this.uploadDetailPics = "filePicker_" + uploadId + "_detailImg";
        this.uploadPreId = "filePicker_" + uploadId + "_pre";
        this.fileSizeLimit = 100 * 1024 * 1024;
        this.picWidth = picWidth;
        this.picHeight = picHeight;
        this.accept = accept;
        this.uploadUrl = uploadUrl;
        this.isMultiple = isMultiple;
        this.multipleSize = multipleSize;
        this.valName = valName;
        this.fn = fn;
    };

    $WebUpload.prototype = {
        /**
         * 初始化webUploader
         */
        init: function() {
            var uploader = this.create();
            this.bindEvent(uploader);
            return uploader;
        },

        /**
         * 创建webuploader对象
         */
        create: function() {

            var webUploader = WebUploader.create({
                auto: true,
                pick: {
                    id: '#' + this.uploadBtnId,
                    multiple: this.isMultiple
                },
                width: this.picWidth,
                height: this.picHeight,
                fileVal: "file",
                accept: this.accept,
                swf: '/plugins/webuploader/Uploader.swf',
                disableGlobalDnd: true,
                duplicate: true,
                server: uploaderUrl,
                fileSingleSizeLimit: this.fileSizeLimit
            });

            return webUploader;
        },

        /**
         * 绑定事件
         */
        bindEvent: function(bindedObj) {
            var me = this;
            bindedObj.on('fileQueued', function(file) {
                var filType = me.accept.title;
                if (filType == "Images") {
                    $("#" + me.uploadDetailPics).remove();
                    var $li = $('<div class="uploadImg"><img>' + '<div class="uploadImg-opr">' + '<a href="javascript:;" onclick="upload_' +me.uploadId+ '.delFile(this)">删除</a>' + '</div>' + '</div>');
                    var $img = $li.find('img');
                    if (me.isMultiple) {
                        if ($("#" + me.uploadPreId + " .uploadImg").length >= me.multipleSize) {
                        	x.error("最多只能上传"+me.multipleSize+"张图片");
                            $("#" + file.id + "_list").remove();
                            return false;
                        }
                        $("#" + me.uploadPreId).append($li);
                    } else {
                        $("#" + me.uploadPreId).html($li);
                    }
                    // 生成缩略图
                    bindedObj.makeThumb(file, function(error, src) {
                        if (error) {
                            $img.replaceWith('<span class="upload-noView">不能预览</span>');
                            return;
                        }
                        $img.attr('src', src);
                    }, me.picWidth, me.picHeight);
                } else {
                	if (me.isMultiple) {
                		if ($("#" + me.uploadPreId + " .file-box").length >= me.multipleSize) {
                			x.error("最多只能上传"+me.multipleSize+"个文件");
                            $("#" + file.id + "_list").remove();
                            return false;
                		}
                	}
                }
            });

            //可以扩展此对象来控制上传头部。
            /* bindedObj.on('uploadBeforeSend', function(obj, data, headers) {
                 $.extend(headers, {
                 "token": token
                 });
             });*/

            // 文件上传过程中创建进度条实时显示。
            bindedObj.on('uploadProgress', function(file, percentage) {
                var filType = me.accept.title;
                var $li = "",
                    $percent;
                if (filType == "Images") {
                    $li = $('#' + file.id + '_list');
                    $percent = $li.find('.uploader-loading');
                    // 避免重复创建uploader-loading-file
                    if (!$percent.length) {
                        $percent = $li.append("<span class='uploader-loading'><em></em></span>");;
                    }
                } else {
                    $li = $('#' + me.uploadPreId);
                    if (!me.isMultiple) {
                    	$li.html("<span class='uploader-loading-file'><em>上传中</em></span>");
                    } else {
                    	$li.append("<span class='uploader-loading-file'><em>上传中</em></span>");
                    }
                }
            });

            // 文件上传成功，给item添加成功class, 用样式标记上传成功。
            bindedObj.on('uploadSuccess', function(file, response) {
                var filType = me.accept.title;
                var result = response.data;
                $('#' + me.uploadPreId).find('.uploader-loading-file').remove();
                if (filType != "Images") {
                	var $li = $('<span id="' + me.pictureId + '_file" class="file-url"></span>');
                    if (me.uploadUrl != "") {
                        $.ajax({
                            type: "post",
                            url: me.uploadUrl,
                            data: {
                                "url": result.url
                            },
                            dataType: 'json',
                            success: function(dataChk) {
                                if (dataChk.result == -1) {
                                    $.ajax({
                                        type: "post",
                                        url: uploaderUrl+"/file/deleteFile",
                                        data: JSON.stringify({"fileName": result.fileId}),
                                        dataType: 'json',
                                        beforeSend: function(request) {
                                            request.setRequestHeader('Content-Type','application/json;charset=utf-8');
                                        },
                                        success: function(dataChk) {}
                                    });
                                    x.error('上传文件格式不对请重新上传！');
                                } else {
                                    $("#" + me.uploadPreId).html($li);
                                    $("#" + me.pictureId + "_file").html(result.fileName);
                                    $("#" + me.pictureId + "_file").attr("href", result.id);
                                    me.fn(response);
                                }
                            }
                        });
                    } else {
                    	if (!me.isMultiple) {
                    		$("#" + me.uploadPreId).html($li);
                            $("#" + me.pictureId + "_file").html(result.fileName);
                            me.fn(response);
                    	} else {
                    		me.fn(response);
                    	}
                    }

                } else {
                    if (me.valName != "" && !me.isMultiple) {
                        $("input[name='" + me.valName + "']").val(result.fileId);
                    }
                    if (me.valName != "" && me.isMultiple) {
                        var valNames = me.valName.split(",");
                        var length = $("#" + me.uploadPreId + " .uploadImg").length;
                        $("#" + me.uploadPreId + " .uploadImg").last().append("<input type='hidden' name='"+valNames[length-1]+"' value='"+result.fileId+"'/>")
                    }
                    me.fn(response, file.id);
                }
            });

            // 文件上传失败，显示上传出错。
            bindedObj.on('uploadError', function(file) {
                //alert("上传失败");
                x.error('上传失败');
            });
            // 其他错误
            bindedObj.on('error', function(type) {
                if ("Q_EXCEED_SIZE_LIMIT" == type) {
                	x.error('文件大小超出了限制');
                } else if ("Q_TYPE_DENIED" == type) {
                	x.error('请选择'+me.accept.extensions+'格式的文件');

                } else if ("Q_EXCEED_NUM_LIMIT" == type) {
                	x.error('上传数量超过限制');
                } else if ("F_DUPLICATE" == type) {
                	x.error('图片选择重复');
                } else {
                	x.error('上传过程中出错');
                }
            });
            // 完成上传完了，成功或者失败
            bindedObj.on('uploadComplete', function(file) {
                $('#' + me.uploadPreId).find('.uploader-loading').remove();
            });
        },
        
        delFile: function(o) {
        	var me = this;
        	var id = $(o).attr("data-id");
        	$(o).parents(".uploadImg").remove();
        	
        	if ($("#" + me.uploadPreId + " .uploadImg").length == 0) {
        		$("#" + me.uploadPreId).html("<img src='/style/admin/img/moren.png' id='" + me.uploadDetailPics + "' width='78' height='78'/>");
            }
        	
        	if (me.valName != ""  && !me.isMultiple) {
                $("input[name='" + me.valName + "']").val("");
            }
        	
        	if (me.valName != ""  && me.isMultiple) {
        		var valNames = me.valName.split(",");
        		$("#" + me.uploadPreId + " input").each(function(index, element) {
                     $(this).attr("name", valNames[index]);
                });
        	}
        }
    };

    window.$WebUpload = $WebUpload;

}());

var file = {
	download : function(fileId, fileName) {
		var aEle = document.createElement("a");// 创建a标签
		aEle.style.display = 'none';
		
        aEle.href = downloadUrl + "?fileId=" + fileId + "&fileName=" + fileName;
        document.body.appendChild(aEle);
        aEle.click();
        document.body.removeChild(aEle);
	},
	preview : function(fileUrl, fileName) {
		var fileType = file.getFileType(fileName);
		
		var win = window;
		console.log(win.parent.layer);
		while(win != top && win.parent.layer) {
			win = win.parent;
		}
		
		switch (fileType) {
		case "txt":
		case "image":
			win.layer.open({
                type: 2,
                title: fileName,
                closeBtn: 1,
                maxmin: true,
                area: ['94%', '94%'],
                //content: [fileUrl, "yes"]
				content: ["/plugins/viewer/viewer.html?file=" + encodeURIComponent(fileUrl), "yes"]
            });
			return;
		case "pdf":
			win.layer.open({
                type: 2,
                title: fileName,
                closeBtn: 1,
                maxmin: true,
                area: ['94%', '94%'],
                content: ["/plugins/pdfJs/web/viewer.html?file=" + encodeURIComponent(fileUrl), "yes"]
            });
			
			return;
		case "word":
		case "excel":
		case "ppt":
			win.layer.open({
                type: 2,
                title: fileName,
                closeBtn: 1,
                maxmin: true,
                area: ['94%', '94%'],
                content: ["https://view.officeapps.live.com/op/view.aspx?src=" + encodeURIComponent(fileUrl), "yes"]
            });
			
			return;

		default:
			break;
		}
		
		x.error("不支持预览的文件");
	},
	getFileType	: function(fileName) {
		// 后缀获取
		let suffix = '';
		// 获取类型结果
		try {
			const flieArr = fileName.split('.');
			suffix = flieArr[flieArr.length - 1];
		} catch (err) {
			suffix = '';
		}
		// fileName无后缀返回 false
		if (!suffix) { return false; }
		suffix = suffix.toLocaleLowerCase();
		
		for(let key in extensions){
			if (extensions[key].find(item => item === suffix)) {
				return key;
			}
　　　　　}
		
		return "";
	}
}

